import request from '@/utils/request'
import { API_CONFIG } from '@/config'
import { BaseApiService, ApiService } from './base'
import type { Camera, VideoRecord, PageQuery, PageResponse } from '@/types'
import { getUser } from '@/utils/auth'

// 目录管理-获取所有目录
export function getCameraTree() {
  if (getUser().id===1) {
    return request.get(API_CONFIG.ENDPOINTS.Device_Menu.ALL_MENU)
  } else {
    return request.get(API_CONFIG.ENDPOINTS.Device_Menu.ALL_MENU_COUNT)
  }
}
//
/**
 * 获取摄像头列表
 */
export function getCameraList(params: PageQuery & { status?: string; location?: string }) {
  return request.get<PageResponse<Camera>>(API_CONFIG.ENDPOINTS.CAMERA.LIST, params)
}

/**
 * 获取摄像头详情
 */
export function getCameraDetail(id: number) {
  return request.get<Camera>(API_CONFIG.ENDPOINTS.CAMERA.DETAIL(id))
}

/**
 * 创建摄像头
 */
export function createCamera(data: Partial<Camera>) {
  return request.post<Camera>(API_CONFIG.ENDPOINTS.CAMERA.LIST, data)
}

/**
 * 更新摄像头
 */
export function updateCamera(id: number, data: Partial<Camera>) {
  return request.put<Camera>(API_CONFIG.ENDPOINTS.CAMERA.DETAIL(id), data)
}

/**
 * 删除摄像头
 */
export function deleteCamera(id: number) {
  return request.delete(API_CONFIG.ENDPOINTS.CAMERA.DETAIL(id))
}

/**
 * 获取摄像头实时状态
 */
export function getCameraStatus(id: number) {
  return request.get<{ status: string; lastHeartbeat: string }>(API_CONFIG.ENDPOINTS.CAMERA.STATUS(id))
}

/**
 * 获取摄像头录像列表
 */
export function getCameraRecords(cameraId: number, params: { startTime: string; endTime: string }) {
  return request.get<VideoRecord[]>(API_CONFIG.ENDPOINTS.CAMERA.RECORDS(cameraId), params)
}

/**
 * 开始录制
 */
export function startRecording(cameraId: number) {
  return request.post(API_CONFIG.ENDPOINTS.CAMERA.START_RECORD(cameraId))
}

/**
 * 停止录制
 */
export function stopRecording(cameraId: number) {
  return request.post(API_CONFIG.ENDPOINTS.CAMERA.STOP_RECORD(cameraId))
}

/**
 * 获取视频播放地址
 */
export function getVideoUrl(cameraId: number, type: 'live' | 'hls' = 'live') {
  return request.get<{ url: string }>(API_CONFIG.ENDPOINTS.CAMERA.VIDEO_URL(cameraId, type))
}

/**
 * 云台控制
 */
export function ptzControl(cameraId: number, action: {
  direction: 'up' | 'down' | 'left' | 'right' | 'zoomIn' | 'zoomOut' | 'focusNear' | 'focusFar'
  speed?: number
}) {
  return request.post(API_CONFIG.ENDPOINTS.CAMERA.PTZ_CONTROL(cameraId), action)
}

/**
 * 设置预置位
 */
export function setPreset(cameraId: number, presetId: number, name: string) {
  return request.post(API_CONFIG.ENDPOINTS.CAMERA.PRESETS(cameraId), { presetId, name })
}

/**
 * 调用预置位
 */
export function gotoPreset(cameraId: number, presetId: number) {
  return request.post(API_CONFIG.ENDPOINTS.CAMERA.GOTO_PRESET(cameraId, presetId))
}

/**
 * 获取摄像头预置位列表
 */
export function getPresets(cameraId: number) {
  return request.get<Array<{ id: number; name: string }>>(API_CONFIG.ENDPOINTS.CAMERA.PRESETS(cameraId))
}

/**
 * 摄像头管理服务类
 * 继承基础API服务类，提供通用CRUD操作
 */
export class CameraService extends BaseApiService<Camera> {
  constructor() {
    super(API_CONFIG.ENDPOINTS.CAMERA.LIST)
  }

  /**
   * 批量获取摄像头状态
   */
  async batchGetStatus(cameraIds: number[]) {
    const promises = cameraIds.map(id => getCameraStatus(id))
    const results = await Promise.all(promises)
    return results
  }

  /**
   * 安全获取视频流地址
   */
  async safeGetVideoUrl(cameraId: number, type: 'live' | 'hls' = 'live') {
    return ApiService.safeCall(
      () => getVideoUrl(cameraId, type),
      { url: '' } // fallback
    )
  }

  /**
   * 智能重试PTZ控制
   */
  async smartPtzControl(cameraId: number, action: {
    direction: 'up' | 'down' | 'left' | 'right' | 'zoomIn' | 'zoomOut' | 'focusNear' | 'focusFar'
    speed?: number
  }) {
    return ApiService.retryCall(() => ptzControl(cameraId, action), 2, 500)
  }

  /**
   * 获取多个摄像头的详细信息
   */
  async getMultipleCameras(cameraIds: number[]) {
    const apiCalls = cameraIds.reduce((acc, id) => {
      acc[`camera_${id}`] = () => getCameraDetail(id)
      return acc
    }, {} as Record<string, () => Promise<any>>)
    
    return ApiService.parallel(apiCalls)
  }
}